package com.longrise.android.byjk.plugins.vip;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.plugins.main.MainActivity;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.MessageConstants;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.event.MineRefreshEvent;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.ActivityUtil;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.DialogUtil;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by callxkj on 2017/1/8.
 * 会员说明&升级页面
 */

public class VipDescriptionActivity extends BaseActivity implements View.OnClickListener {

    private ViewPager mVp;
    private Context mContext;
    private RelativeLayout mRlbt;
    private TextView mTvdeadline;
    public static final String MODE = "mode";//从哪个页面进来
    public static final int LOGIN = 1;   //登录的时候
    public static final int ABOUT_ME = 2; // 我的页面
    public static final int HOME_PAGE = 3; //首页
    public int mFlag;
    private Toolbar mToolbar;

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_vipdescription;
    }

    @Override
    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle("会员中心");
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.by_ic_close_black);

        mRlbt = (RelativeLayout) findViewById(R.id.vip_bt_rl);
        mVp = (ViewPager) findViewById(R.id.vip_vp);
        mTvdeadline = (TextView) findViewById(R.id.vip_deadline);

        Intent intent = getIntent();
        mFlag = intent.getIntExtra(MODE, 0);
        mContext = this;

        initData();
        initViewPager();
        initEvent();
    }

    private void initData() {
        int viptype = UserInfor.getInstance().getViptype();
        int remainingdays = UserInfor.getInstance().getRemainingdays();
        if (viptype == VipType.VIP_1) { //普通会员需要升级
            mRlbt.setVisibility(View.VISIBLE);
        } else if (viptype == VipType.VIP_3) { //至尊会员
            mRlbt.setVisibility(View.GONE);
        }
        mTvdeadline.setText(getResources().getText(R.string.before_update_msg));
    }

    private void initViewPager() {
        mVp.setPageMargin(AppUtil.dip2px(16));
        mVp.setOffscreenPageLimit(3);
        mVp.setAdapter(new VipPagerAdapter());
        mVp.setCurrentItem(1);
    }

    private void initEvent() {
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toClose();
            }
        });
        mRlbt.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.vip_bt_rl: //免费升级按钮
                toUpgrade();
                break;
        }
    }

    /**
     * 点击叉叉或者返回按钮
     */
    private void toClose() {
        if (mFlag == LOGIN) {
            ActivityUtil.removeActivity(this);
            ActivityUtil.finishAllAcivity();
            Intent loginIntent = new Intent(VipDescriptionActivity.this, MainActivity.class);
            startActivity(loginIntent);
        } else if (mFlag == ABOUT_ME) {
            MineRefreshEvent event = new MineRefreshEvent();
            event.setVipIcon(true);
            EventBus.getDefault().post(event);
        } else if (mFlag == HOME_PAGE) {
//            if (UserInfor.getInstance().getViptype() == 3) {
//                Intent intent = new Intent();
//                intent.setAction(MessageConstants.HOME_VIP_UPDATE);
//                sendBroadcast(intent);
//            }
        }
        finish();
    }

    /**
     * 去升级VIP
     */
    private void toUpgrade() {
        EntityBean bean = new EntityBean();
        String userid = UserInfor.getInstance().getUserid();
        String usersfzh = UserInfor.getInstance().getUsersfzh();
        String personname = UserInfor.getInstance().getPersonname();
        String userNickName = UserInfor.getInstance().getUserNickName();
        bean.set("userid", userid);
        bean.set("renewDays", 1);
        bean.set("viptype", 3);
        bean.set("cardno", usersfzh);
        bean.set("personname",personname);
        bean.set("nickname",userNickName);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        mRlbt.setClickable(false);
        DZZWTools.showWaitDialog(VipDescriptionActivity.this);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl,
                "bbt_renewVipUserAndCreateDynamic", fbean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    if (result != null) {
                        EntityBean bean = (EntityBean) result;
                        String resultdesc = (String) bean.get("resultdesc");
                        int resultstate = (Integer) bean.get("resultstate");
                        if (resultstate == 1) {
                            UserInfor userInfor = UserInfor.getInstance();
                            EntityBean resultBean = bean.getBean("result");
                            //会员类型
                            Integer viptype = resultBean.getInt("viptype");
                            userInfor.setViptype(viptype);
                            //会员类型名称
                            String viptypename = resultBean.getString("viptypename");
                            userInfor.setViptypename(viptypename);
                            //截止日期
                            String deadline = resultBean.getString("deadline");
                            String[] split = deadline.split(" ");
                            userInfor.setDeadline(split[0].replace("-", "/"));
                            //剩余天数
                            Integer remainingdays = resultBean.getInt("remainingdays");
                            userInfor.setRemainingdays(remainingdays);
                            showSuccessDialog();
                        } else {
                            DZZWTools.showToast(VipDescriptionActivity.this, resultdesc, 0);
                        }
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished(String key, String service) {
                mRlbt.setClickable(true);
                DZZWTools.dismissDialog(null);
            }
        });
    }

    /**
     * 显示开通成功的dialog
     */
    public void showSuccessDialog() {
        View dialogView = View.inflate(this, R.layout.dialog_vip_prime_success, null);
        ImageView bt_iv = (ImageView) dialogView.findViewById(R.id.dialog_vip_bottom_bt);
        final Dialog dialog = DialogUtil.getInstance().creatAlertDialog(this, dialogView, 270, 306);
        bt_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initData();
                dialog.dismiss();
            }
        });
        //返回键消失后 重新init数据
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    initData();
                    dialog.dismiss();
                }
                return false;
            }
        });

        dialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            toClose();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    class VipPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View cardView = View.inflate(mContext, R.layout.item_vipdescription, null);
            ImageView cIv = (ImageView) cardView.findViewById(R.id.item_vipdescription_iv);
            TextView cTitle = (TextView) cardView.findViewById(R.id.item_vipdescription_tv_title);
            TextView cMsg = (TextView) cardView.findViewById(R.id.item_vipdescription_tv_msg);
            int imageId = 0;
            int titleId = 0;
            int msgId = 0;
            int colorId = 0;
            switch (position) {
                case 0:
                    imageId = R.drawable.ic_my_member_analytics;
                    titleId = R.string.title_xqpc;
                    msgId = R.string.msg_xqpc;
                    colorId = R.color.vip_xqpc;
                    break;
                case 1:
                    imageId = R.drawable.ic_my_member_show;
                    titleId = R.string.title_zyx;
                    msgId = R.string.msg_zyx;
                    colorId = R.color.vip_zyx;
                    break;
                case 2:
                    imageId = R.drawable.ic_my_member_customer;
                    titleId = R.string.title_khgl;
                    msgId = R.string.msg_khgl;
                    colorId = R.color.vip_khgl;
                    break;
            }
            if (imageId != 0) {
                cIv.setImageResource(imageId);
            }
            if (titleId != 0) {
                cTitle.setText(mContext.getResources().getText(titleId));
            }
            if (msgId != 0) {
                cMsg.setText(mContext.getResources().getText(msgId));
            }
            if (colorId != 0) {
                cTitle.setTextColor(mContext.getResources().getColor(colorId));
                cMsg.setTextColor(mContext.getResources().getColor(colorId));
            }

            container.addView(cardView);
            return cardView;
        }
    }

}
